package com.example.zhangjy.collweather.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.zhangjy.collweather.R;
import com.example.zhangjy.collweather.db.CollWeatherDB;
import com.example.zhangjy.collweather.model.City;
import com.example.zhangjy.collweather.model.County;
import com.example.zhangjy.collweather.model.Province;
import com.example.zhangjy.collweather.util.HttpCallbackListner;
import com.example.zhangjy.collweather.util.HttpUtil;
import com.example.zhangjy.collweather.util.Utility;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by zhangjy on 2015/8/27.
 */
public class ChooseAreaActivity extends Activity{

    public static final int LEVEL_PROVINCE = 0;
    public static final int LEVEL_CITY = 1;
    public static final int LEVEL_COUNTY = 2;

    private ProgressDialog progressDialog;
    private TextView titleText;
    private ListView listView;
    private ArrayAdapter<String> adapter;

    private CollWeatherDB db;

    private List<String> dataList = new ArrayList<String>();

    private List<Province> provinces;
    private List<City> cities;
    private List<County> counties;


    private Province selectProvince;
    private City selectCity;

    private int currentLevel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.choose_area);

        listView = (ListView) findViewById(R.id.list_view);
        titleText = (TextView) findViewById(R.id.title_text);

        adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,dataList);

        listView.setAdapter(adapter);

        db = CollWeatherDB.getInstance(this);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if(currentLevel == LEVEL_PROVINCE) {
                    selectProvince = provinces.get(position);
                    queryCitys();
                }
                else if(currentLevel == LEVEL_CITY) {
                    selectCity = cities.get(position);
                    queryCountys();
                }
            }
        });

        queryProvinces();

    }

    /**
     * 加载省份数据，先从数据库中查询，没有再调用服务
     */
    private void queryProvinces() {

        provinces = db.loadProvinces();

        if (provinces.size() > 0) {

            dataList.clear();

            for (Province province : provinces) {
                dataList.add(province.getProvinceName());
            }

            adapter.notifyDataSetChanged();
            listView.setSelection(0);
            titleText.setText("中国");
            currentLevel = LEVEL_PROVINCE;

        } else {

            queryFromServer(null,"province");
        }


    }

    /**
     * 加载市数据，先从数据库中查询，没有再调用服务
     */
    private void queryCitys() {

        cities = db.loadCitys(selectProvince.getId());
        if (cities.size() > 0) {
            dataList.clear();
            for (City city : cities) {
                dataList.add(city.getCityName());
            }

            adapter.notifyDataSetChanged();
            listView.setSelection(0);
            titleText.setText(selectProvince.getProvinceName());
            currentLevel = LEVEL_CITY;

        } else {

            queryFromServer(selectProvince.getProvinceCode(),"city");

        }


    }

    /**
     * 加载县数据，先从数据库中查询，没有再调用服务
     */
    private void  queryCountys() {

        counties = db.loadCounty(selectCity.getId());
        
        if(counties.size() > 0) {
            
            dataList.clear();
            for (County county : counties) {
                dataList.add(county.getCountyName());
            }
            
            adapter.notifyDataSetChanged();
            
            listView.setSelection(0);
            titleText.setText(selectCity.getCityName());
            
            currentLevel = LEVEL_COUNTY;
            
        } else {
            queryFromServer(selectCity.getCityCode(),"county");
        }
    }

    /**
     * 从服务端查询省、市、县数据
     * @param code 省、市编号
     * @param type 查询类型
     */
    private void queryFromServer(final String code, final String type) {

        String address;
        if(!TextUtils.isEmpty(code)) {
            address = "http://www.weather.com.cn/data/list3/city" + code + ".xml";
        } else {
            address = "http://www.weather.com.cn/data/list3/city.xml";
        }

        showProgressDialog();

        HttpUtil.sendHttpRequest(address, new HttpCallbackListner() {
            @Override
            public void onFinish(String response) {
                boolean result = false;
                if ("province".equals(type)) {
                    result = Utility.handleProvinceResponse(db,response);
                } else if("city".equals(type)) {
                    result = Utility.handleCityResponse(db,response,selectProvince.getId());
                } else if("county".equals(type)) {
                    result = Utility.handleCountyResponse(db,response,selectCity.getId());
                }

                if (result) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            closeProgressDialog();
                            if ("province".equals(type)) {
                                queryProvinces();
                            } else if("city".equals(type)) {
                                queryCitys();
                            } else if("county".equals(type)) {
                                queryCountys();
                            }
                        }
                    });
                }
            }

            @Override
            public void onError(Exception e) {

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        closeProgressDialog();
                        Toast.makeText(ChooseAreaActivity.this,"加载失败",Toast.LENGTH_LONG).show();
                    }
                });

            }
        });

    }

    private void closeProgressDialog() {

        if (progressDialog != null) {
            progressDialog.dismiss();
        }

    }

    private void showProgressDialog() {

        if (progressDialog == null) {
            progressDialog = new ProgressDialog(this);
            progressDialog.setMessage("正在加载..........");
            progressDialog.setCanceledOnTouchOutside(false);
        }

        progressDialog.show();

    }

    @Override
    public void onBackPressed() {
        if (currentLevel == LEVEL_CITY) {
            queryProvinces();
        } else  if (currentLevel == LEVEL_COUNTY) {
            queryCitys();
        } else {
            finish();
        }
    }
}
